package backend;

import gui.Shortcut;
import gui.ShortcutButton;
import gui.ShortcutFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Comment;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class XMLCommunicator {
	private static String ID = "ID";
	private static String PATH = "Path";
	private static String TITILE = "Title";
	private static String GROUP = "Group";
	File xmlFile;

	public XMLCommunicator() {
		xmlFile = new File(PathHandler.GetLocalPath()
				+ PathHandler.SHORTCUTS_XML);
		if (!xmlFile.exists()) {
			createXML();
		}
	}

	public Vector<Shortcut> getShortcuts(Vector<Shortcut> shortcuts,ShortcutFactory factory) {
		try {

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(xmlFile);
			Element root_element = doc.getDocumentElement();
			NodeList node_list = root_element.getChildNodes();
			for (int i = 0; i < node_list.getLength(); i++) {
				if (node_list.item(i).getAttributes() != null) {
					String id = null;
					String execPath = null;
					String displayTitle = null;
					String group = null;
					NamedNodeMap attributes = node_list.item(i).getAttributes();
					for (int j = 0; j < attributes.getLength(); j++) {
						Node attribute = attributes.item(j);
						if (attribute.getNodeName().equals(ID))
							id = attribute.getNodeValue();
						else if (attribute.getNodeName().equals(PATH))
							execPath = attribute.getNodeValue();
						else if (attribute.getNodeName().equals(TITILE))
							displayTitle = attribute.getNodeValue();
						else if (attribute.getNodeName().equals(GROUP))
							group = attribute.getNodeValue();
					}
					File file = new File(execPath);
					if (file.exists()) {
						shortcuts.add(factory.createShortcut(id, execPath, displayTitle, group));
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return shortcuts;
	}

	private void writeChanges(Document doc) throws FileNotFoundException,
			TransformerException {
		Source xmlSource = new DOMSource(doc);

		// create StreamResult for transformation result
		StreamResult result = new StreamResult(new FileOutputStream(xmlFile
				.getAbsolutePath().replace("%20", " ")));

		// create TransformerFactory
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();

		// create Transformer for transformation
		Transformer transformer = transformerFactory.newTransformer();

		transformer.setOutputProperty("indent", "yes");

		// transform and deliver content to client
		transformer.transform(xmlSource, result);
	}

	public void addShortcut(String id, String path, String title, String group) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(xmlFile);

			Element root = doc.getDocumentElement();
			Element shortcut = doc.createElement("Shortcut");
			shortcut.setAttribute(ID, id);
			shortcut.setAttribute(PATH, path);
			shortcut.setAttribute(TITILE, title);
			shortcut.setAttribute(GROUP, group);
			root.appendChild(shortcut);

			this.writeChanges(doc);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void removeShortcut(String id) {
		try {

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(xmlFile);
			Element root = doc.getDocumentElement();
			NodeList node_list = root.getChildNodes();
			for (int i = 0; i < node_list.getLength(); i++) {
				if (node_list.item(i).getAttributes() != null) {
					try {
						if (id.equals(node_list.item(i).getAttributes()
								.getNamedItem(ID).getNodeValue())) {
							root.removeChild(node_list.item(i));
							break;
						}

					} catch (NullPointerException e) {
						// ignore
					}
				}
			}
			this.writeChanges(doc);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void renameShortcut(String id, String newTitle) {
		try {

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(xmlFile);
			Element root = doc.getDocumentElement();
			NodeList node_list = root.getChildNodes();
			for (int i = 0; i < node_list.getLength(); i++) {
				if (node_list.item(i).getAttributes() != null) {
					try {
						if (id.equals(node_list.item(i).getAttributes()
								.getNamedItem(ID).getNodeValue())) {
							node_list.item(i).getAttributes().getNamedItem(
									TITILE).setNodeValue(newTitle);
						}
					} catch (NullPointerException e) {
						// ignore
					}
				}
			}
			this.writeChanges(doc);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void createXML() {
		try {
			Writer output = null;
			output = new BufferedWriter(new FileWriter(xmlFile));
			output.write("<?xml version='1.0' encoding='UTF-8'?>");
			output.write("<Shortcuts>");
			output.write("</Shortcuts>");
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}